﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Text.RegularExpressions;

namespace Common
{
    public static class StringHelper
    {
        public static string ChangeEmptyToNull(this string str)
        {            
            return string.IsNullOrEmpty(str) ? null : str;
        }

        public static bool IsInt(this string str)
        {
            Regex reg = new Regex(@"^\d+$");
            return reg.IsMatch(str);
        }

        public static bool IsIPAddress(this string str)
        {
            Regex reg = new Regex(@"^([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$");
            return reg.IsMatch(str);
        }

        public static byte[] HexStringToByte(this string hexString)
        {
            byte[] bytes = new byte[hexString.Length / 2];

            for (int i = 0; i < bytes.Length; i++)
            {
                bytes[i] = Convert.ToByte(hexString.Substring(2 * i, 2), 16);
            }
            return bytes;
        }

        public static string SafeUrlEnd(this string str)
        {
            if (string.IsNullOrEmpty(str) || str.EndsWith("/"))
            {
                return str;
            }
            else
            {
                return str + "/";
            }
        }

        public static string ToMD5(this string str)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] fromData = System.Text.Encoding.UTF8.GetBytes(str);
            byte[] targetData = md5.ComputeHash(fromData);
            string byte2String = null;

            for (int i = 0; i < targetData.Length; i++)
            {
               byte2String += targetData[i].ToString("x2");
            }
            return byte2String;
        }
    }
}
